package com.jinly.ryder.ssh.service.impl;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jinly.ryder.common.error.SystemErrorType;
import com.jinly.ryder.ssh.command.FileListCommand;
import com.jinly.ryder.ssh.command.SshSessionUtil;
import com.jinly.ryder.ssh.command.model.FileInfo;
import com.jinly.ryder.ssh.service.SshFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SshFileServiceImpl implements SshFileService {

    @Override
    public List<FileInfo> fileList(String host, int port, String dir) {
        Session sshSession = null;
        try {
            sshSession = SshSessionUtil.connectSession(host, port);
            FileListCommand fileListCommand = new FileListCommand(sshSession);
            List<FileInfo> list = fileListCommand.exec(dir);
            return list.stream().sorted(Comparator.comparing(FileInfo::getFileType)
                    .thenComparing(FileInfo::getModifyTime).reversed()).collect(Collectors.toList());
        } catch (Exception e) {
            log.warn("ssh file close:{}", e.getMessage());
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError();
        } finally {
            SshSessionUtil.closeSession(sshSession);
        }
        return null;
    }

    @Override
    public void getFile(String host, int port, String fileName, String dest) {
        Session sshSession = null;
        ChannelSftp channelSftp = null;
        try {
            sshSession = SshSessionUtil.connectSession(host, port);
            channelSftp = (ChannelSftp) sshSession.openChannel("sftp");
            channelSftp.connect();
            channelSftp.get(fileName, dest);
        } catch (Exception e) {
            log.warn("ssh get file close:{}", e.getMessage(), e);
            SystemErrorType.INTERNAL_SERVER_ERROR.throwError();
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            SshSessionUtil.closeSession(sshSession);
        }

    }
}
